package com.caogt.programmer.qm.question.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.caogt.programmer.qm.question.entity.Question;
import com.caogt.programmer.qm.question.mapper.QuestionMapper;
import com.caogt.programmer.qm.question.service.IQuestionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.programmer.common.enums.QuestionStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.SecureRandom;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author caogt
 * @since 2020-01-05
 */
@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements IQuestionService {

    @Autowired
    private QuestionMapper questionMapper;
    private SecureRandom random = new SecureRandom();
    @Override
    public void saveQuestion(Question question) {
        questionMapper.insert(question);
    }

    @Override
    public void updateQuestionById(Question question) {
        questionMapper.updateById(question);
    }

    @Override
    public void deleteById(Long id) {
        questionMapper.deleteById(id);
    }

    @Override
    public List<Question> selectByCategory(Long categoryId) {
        return selectByParam("category_id",categoryId,-1);
    }

    @Override
    public List<Question> selectByCategory(Long categoryId, int size) {
        if(size < 1){
            return null;
        }
        return selectByParam("category_id",categoryId,size);
    }

    @Override
    public List<Question> selectByLevel(Long levelId) {
        return selectByParam("level_id",levelId,-1);
    }

    @Override
    public List<Question> selectByLevel(Long levelId, int size) {
        if(size < 1){
            return null;
        }
        return selectByParam("level_id",levelId,size);
    }

    private List<Question> selectByParam(String fieldName,Long value,int size){

        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(fieldName,value);
        queryWrapper.eq("status", QuestionStatus.normal.getCode());
        if(size == -1){
            return questionMapper.selectList(queryWrapper);
        }

        int allCount = questionMapper.selectCount(queryWrapper);
        if(size >= allCount){
            return questionMapper.selectList(queryWrapper);
        }

        Page<Question> page = new Page<>();
        int totalPages = allCount/size;
        page.setSize(size);
        page.setCurrent(random.nextInt(totalPages));

        return questionMapper.selectPage(page, queryWrapper).getRecords();
    }

}
